import Axios from 'axios';
import { ConfigService } from '@nestjs/config';
import { Class_HttpException_Base } from '@/common/classes/httpException';
import { Injectable } from '@nestjs/common';
import {
  wxChat_UserInfoAccessTokenReturn_OthClass,
  wxChat_UserInfoReturn_OthClass,
} from './assets/wxChat.class';

@Injectable()
export class WxChat_Service {
  private readonly appId: string;
  private readonly appSecret: string;
  constructor(private configService: ConfigService) {
    this.appId = this.configService.get<string>('WXPUBLIC_APPID');
    this.appSecret = this.configService.get<string>('WXPUBLIC_APPSECRET');
  }

  wechat_Login(
    redirectUri: string,
    scope: 'snsapi_login' | 'snsapi_userinfo' = 'snsapi_userinfo',
  ): string {
    return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`;
  }

  async wechat_UserInfo(code: string): Promise<wxChat_UserInfoReturn_OthClass> {
    const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appId}&secret=${this.appSecret}&code=${code}&grant_type=authorization_code`;
    const accessTokenData: wxChat_UserInfoAccessTokenReturn_OthClass = await Axios.get(url);
    if (!accessTokenData.data.access_token) {
      throw new Class_HttpException_Base('授权失败');
    }
    const urld = `https://api.weixin.qq.com/sns/userinfo?access_token=${accessTokenData.data.access_token}&openid=${accessTokenData.data.openid}&lang=zh_CN`;
    const userinfp = (await Axios.get(urld)) as wxChat_UserInfoReturn_OthClass;
    if (userinfp.data?.errcode) throw new Class_HttpException_Base(userinfp.data.errmsg);
    return userinfp;
  }
}
